package com.ccpdown.util.file;

import com.ccpdown.util.xml.CtrXmlUtil;
import com.ccpdown.vo.Software;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.Toast;

public class Updater {
	
	private static Software sw;
	private static Context context;

	public static void checkUpdate(Context context, String path) {
		try {
			Updater.context=context;
			sw = CtrXmlUtil.getUpdate(path);
			if (context.getPackageManager().getPackageInfo("com.ccpdown.view", 0).versionName
					.equals(sw.version)) {
				openEmptyDialog();
			} else {
				openOptionsDialog();
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT);
			((Activity) context).finish();
		}
	}
	
	private static void openOptionsDialog() {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle("本软件发现新版本");
		builder.setMessage("本软件最新版本为:" + sw.version + "\n是否下载本软件的最新版本");
		builder.setPositiveButton("下载最新版本",
				new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						FileDownUtil fd = new FileDownUtil(context);
						fd.getFile(sw.pathStr);
					}
				});
		builder.setNegativeButton("继续使用",
				new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		builder.show();
	}
	
	private static void openEmptyDialog(){
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle("本软件已是最新版本");
		builder.setMessage("本软件已是最新版本\n无需升级");
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		builder.show();
	}
}
